from app.schema.base import RespBaseSchema, RespDataSchema
from app.service.base import BaseService
from app.service.ai import AiService
from app.schema.chat import *
from app.dao.chat import ChatDao
from app.dao.user import UserDao
from app.dao.ai import AiDao
from app.dao.message import MessageDao
from app.model.chat import Chat
from app.schema.message import MessageInfoSchema
from app.schema.base import *


import asyncio
import json


class ChatService(BaseService):
    def __init__(self, auth_data: dict = {}):
        user_id = auth_data.id
        self.Model = Chat
        self.dao = ChatDao(user_id)
        self.dao.Model = Chat

        super().__init__(user_id, auth_data)

    async def create_chat(self, chat: ChatInfoSchema, auth_data: dict = {}):
        ai_info = AiDao().search_by_ai_id(chat.ai_id)
        if ai_info is None:
            return RespBaseSchema(code=40001, message='AI不存在')
        chat.group_id = ai_info.user_id
        # if ai_info.user_id == self.user_id:
        #     return RespBaseSchema(code=40002, message='不能和自己聊天') #用户可以体验自己AI
        chat_info = self.dao.search_chat(chat.ai_id, chat.user_id)
        if chat_info:
            return RespDataSchema(data={'chat_id': chat_info.id, "name":ai_info.name, "avatar":ai_info.avatar})
        
        chat_id = self.dao.create_chat(chat)

        # 创建聊天的同时，创建聊天默认消息
        group_info = UserDao(self.user_id).read(ai_info.user_id)
        qr_content = json.dumps(
            {
                'name': group_info.name,
                'avatar': group_info.avatar,
                "info":ai_info.info
            }
        )
        messageDao = MessageDao()
        qr_message = MessageDao.Model(user_id = chat.ai_id, chat_id = chat_id.id, message_type = 1, content = qr_content, user_type = 1)
        greet_message = MessageDao.Model(user_id = chat.user_id, chat_id = chat_id.id, message_type = 2, content = ai_info.greet, user_type = 1)
        messageDao.create(qr_message)
        messageDao.create(greet_message)

        # 修改last_message_id
        await self.read_message(chat_id.id)
        # 修改add_num数据
        aidao = AiDao()
        ai = aidao.read(ai_info.id)
        ai.add_num += 1
        aidao.update(ai)

        return RespDataSchema(data={'chat_id': chat_id.id, "name":ai_info.name, "avatar":ai_info.avatar})
        
    async def get_chat_list(self,args:ListArgsSchema,auth_data: dict):
        args.filters = [
            ListFilterSchema(key='group_id', value=auth_data.id, condition='=')
        ]
        args.keys = [
            ListKeySchema(key='id'),
            ListKeySchema(key='user_id'),
            ListKeySchema(key='last_msg_id')
        ]
        # 聊天列表
        chat_list=self.list(args)

        ans = []
        for chat in chat_list.list:
            user_info = UserDao().read(chat["user_id"])

            # 获取未读消息数
            message_args = ListArgsSchema(size=100)
            if chat["last_msg_id"] is not None:
                message_args.filters = [
                    ListFilterSchema(key='id', value=chat["last_msg_id"], condition='>')
                ]
            message_list = MessageDao().read_list(message_args)

            user = {
                'user_id': user_info.id,
                'name': user_info.name,
                'avatar': user_info.avatar,
                'unread': len(message_list.list),
                'chat_id': chat["id"]
            }
            ans.append(user)

        # 修改add_num数据, 清空
        if args.page == 1:
            ai_info = AiDao().read_by_user_id(auth_data.id)
            ai = AiDao().read(ai_info.id)
            ai.add_num = 0
            AiDao().update(ai)

        return {"list": ans, "page_count":chat_list.page_count}
        
    async def read_message(self,chat_id:int):
        message = await MessageDao().search_by_chat_id(chat_id)
        chat = self.dao.read(chat_id)
        chat.last_msg_id = message.id
        self.dao.update(chat)

    async def get_ai_list(self, args:ListArgsSchema, auth_data:dict):
        args.user_id = auth_data.id
        args.keys = [ListKeySchema(key='id'), ListKeySchema(key='ai_id')]
        chat_list = self.list(args)
        ans = []
        for chat in chat_list.list:
            ai_info = AiDao().read(chat['ai_id'])
            if ai_info is not None:
                ans.append({
                    "id": ai_info.id,
                    "name": ai_info.name,
                    "avatar": ai_info.avatar
                    })

        return RespDataSchema(data={"list": ans, "page_count": chat_list.page_count})